/***********************************************************************
 *            Project: CoreCms
 *        ProjectName: 核心内容管理系统                                
 *                Web: https://www.corecms.net                      
 *             Author: 大灰灰                                          
 *              Email: jianweie@163.com                                
 *         CreateTime: 2021/1/31 21:45:10
 *        Description: 暂无
 ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.DTO;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.Entities.Expression;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.DTO;
using CoreCms.Net.Model.ViewModels.UI;
using Essensoft.Paylink.Alipay.Domain;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SqlSugar;


namespace CoreCms.Net.Services
{
    /// <summary>
    /// 拼团规则表 接口实现
    /// </summary>
    public class CoreCmsPinTuanRuleServices : BaseServices<CoreCmsPinTuanRule>, ICoreCmsPinTuanRuleServices
    {
        private readonly ICoreCmsPinTuanRuleRepository _dal;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IServiceProvider _serviceProvider;

        public CoreCmsPinTuanRuleServices(IUnitOfWork unitOfWork, ICoreCmsPinTuanRuleRepository dal,
            IServiceProvider serviceProvider
            )
        {
            this._dal = dal;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
            _serviceProvider = serviceProvider;
        }


        /// <summary>
        /// 取购物车数据的时候，更新价格
        /// </summary>
        /// <param name="list"></param>
        /// <param name="ruleId">规则序列</param>
        /// <returns></returns>
        public WebApiCallBack PinTuanInfo(List<CartProducts> list, int ruleId)
        {
            return _dal.PinTuanInfo(list,ruleId);
        }


        /// <summary>
        /// 接口上获取拼团所有商品
        /// </summary>
        /// <returns></returns>
        public async Task<WebApiCallBack> GetPinTuanList(int userId = 0, int pageIndex = 1, int pageSize = 20)
        {
            var jm = new WebApiCallBack();

            using var container = _serviceProvider.CreateScope();
            var pinTuanGoodsServices = container.ServiceProvider.GetService<ICoreCmsPinTuanGoodsServices>();
            var pinTuanRuleServices = container.ServiceProvider.GetService<ICoreCmsPinTuanRuleServices>();
            var goodsServices = container.ServiceProvider.GetService<ICoreCmsGoodsServices>();

            //从缓存中获取有效的数据
            var dt = DateTime.Now;
            var pinTuanRules = await pinTuanRuleServices.QueryListByClauseAsync(p => p.isStatusOpen == true && p.startTime < dt && p.endTime > dt, p => p.sort, OrderByType.Asc, true, true, 24 * 60);
            if (pinTuanRules == null && !pinTuanRules.Any())
            {
                jm.status = true;
                jm.data = null;
                return jm;
            }
            //获取开启的规则集序列
            var pinTuanRuleIds = pinTuanRules.Select(p => p.id).ToArray();


            var dtoData = await _dal.GetPinTuanInfos(pinTuanRuleIds, p => p.sortId, OrderByType.Asc, pageIndex, pageSize);
            foreach (var item in dtoData)
            {
                //判断拼团状态
                var dtNow = DateTime.Now;
                if (item.startTime > dt)
                {
                    item.startStatus = (int)GlobalEnumVars.PinTuanRuleStatus.notBegun;
                    var ts = item.startTime.Subtract(dt);
                    item.timestamp = (int)ts.TotalSeconds;
                }
                else if (item.startTime <= dt && item.endTime > dt)
                {
                    item.startStatus = (int)GlobalEnumVars.PinTuanRuleStatus.begin;
                    var ts = item.endTime.Subtract(dt);
                    item.timestamp = (int)ts.TotalSeconds;
                }
                else
                {
                    item.startStatus = (int)GlobalEnumVars.PinTuanRuleStatus.haveExpired;
                }

                item.pinTuanPrice -= item.discountAmount;
            }

            jm.data = dtoData;
            jm.status = true;
            return jm;
        }

        /// <summary>
        ///     根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public async Task<IPageList<TagPinTuanResult>> QueryTagPinTuanPageAsync(Expression<Func<TagPinTuanResult, bool>> predicate,
            Expression<Func<TagPinTuanResult, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1, int pageSize = 20)
        {
            return await _dal.QueryTagPinTuanPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize);
        }



        /// <summary>
        ///     根据规则Id获取拼团相关信息
        /// </summary>
        /// <param name="ruleId">规则序列</param>
        /// <returns></returns>

        public async Task<TagPinTuanResult> GetPinTuanInfo(int ruleId)
        {
            return await _dal.GetPinTuanInfo(ruleId);
        }


        /// <summary>
        ///     根据规则ID数组获取拼团相关信息
        /// </summary>
        /// <param name="ruleIds">规则序列</param>
        /// <param name="orderByExpression"></param>
        /// <param name="orderByType"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<IPageList<PinTuanListDTO>> GetPinTuanInfos(int[] ruleIds,
            Expression<Func<PinTuanListDTO, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20)
        {

            return await _dal.GetPinTuanInfos(ruleIds, orderByExpression, orderByType, pageIndex, pageSize);

        }

    }
}
